# -*- coding: utf-8 -*-
# @Date    : 2017-04-25 14:12:51
# @Author  : fancy (fancy@thecover.co)
import time
import json
import markdown
from sqlalchemy import desc

from flask_login import current_user, login_required
from flask import request, render_template, session, abort, redirect, \
    url_for

from app import app, db
from .models import Post, Comment
from ..utils.common_tools import get_now

def get_page(count, perpage=50):
    return count/perpage + (1 if count%perpage>0 else 0)


@app.route('/', methods=['GET'])
def index():
    posts = Post.query.order_by(desc("pub_date")).limit(20)
    data = {
        'posts': posts,
        'show_node_navi': True,
    }
    return render_template('index.html', **data)

@app.route('/t/<int:post_id>', methods=['GET', 'POST'])
def detail(post_id):
    post = Post.query.filter_by(id=post_id).first_or_404()
    post.views += 1
    db.session.commit()
    cur_page = request.args.get('page', 1)
    paginate = post.comments.paginate(
        page=cur_page, per_page=50, error_out=False)
    comments = paginate.items
    page_count = get_page(post.comment_count)
    if page_count < 3:
        page_list = range(1, page_count+1)
    else:
        page_list = [1, 2, 3]
        page_list.append(-1)
        page_list.append(page_count)
    data = {
        'post': post,
        'comments': comments,
        'page_list': page_list,
        'show_node_navi': False,
        'paginate': paginate,
        'now': get_now(),
    }
    return render_template('detail.html', **data)


@app.route('/addComment', methods=['POST'])
@login_required
def add_comment():
    if request.method == 'POST':
        form = request.form
        content = form.get('content')
        result = {'status': 0, 'msg': 'success'}
        if not content:
            result['status'] = 1
            result['msg'] = 'No Content'
            return json.dumps(result)
        post_id = int(form.get('post_id'))
        post = Post.query.filter_by(id=post_id).first()
        if not post:
            result['status'] = 2
            result['msg'] = 'Something wrong~'
            return json.dumps(result)
        post.comment_count += 1
        comment = Comment(content=form.get('content'),
            author_id=current_user.id, post_id=int(form.get('post_id')))
        db.session.add(comment)
        db.session.commit()
        # result['comment_id'] = comment.id
        # return json.dumps(result)
        return redirect(url_for('detail', post_id=post_id))


@app.route('/new', methods=['GET', 'POST'])
def new_post():
    error = {}
    post = Post(title='', content_source='')
    if request.method == 'GET':
        return render_template('new_post.html', disable_right=True,
            error=error, post=post)
    elif request.method == 'POST':
        form = request.form
        title = form.get('title')
        content_source = request.form.get('content', '')
        if not title:
            error['title'] = u'主题标题不能为空'
        elif len(title) > 120:
            error['title'] = u'主题标题不能超过 120 个字符'
        if len(content_source) > 20000:
            error['content'] = u'主题内容不能超过 20000 个字符'
        post.title = title
        post.content_source = content_source
        if error:
            return render_template('new_post.html', post=post, error=error)
        else:
            content = markdown.markdown(content_source)
            post.user = current_user
            post.content = content
            db.session.add(post)
            db.session.commit()
            return redirect(url_for('detail', post_id=post.id))
